/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MyOwnChat;



import java.net.*;
import java.io.*;

public class ChatClient implements Runnable
{  private Socket socket              = null;
   private Thread thread              = null;
   private DataInputStream  console   = null;
   private DataOutputStream streamOut = null;
   private ChatClientThread client    = null;

   public ChatClient(InetAddress serverIP, int serverPort, String name)
   {
       System.out.println( serverIP.getHostAddress() + " is being set up as new client. Wait....");
       boolean t=true;
       while(t)
          {
          //System.out.println("Trying to connect to "+serverIP.toString().substring(1)+" please wait.........");
          try
          {  socket = new Socket(serverIP, serverPort);
             System.out.println("New Client Connected: " + socket);
             start();
             t=false;
          }
          catch(UnknownHostException uhe)
          {  }//System.out.println("Host unknown: " + uhe.getMessage()); }
          catch(IOException ioe)
          {  }// System.out.println("Unexpected exception: " + ioe.getMessage()); }

            }
   }




   public void run()
   {  while (thread != null)
      {  try
         {  streamOut.writeUTF(console.readLine());
            streamOut.flush();
            System.out.println("waiting for input to send");
         }
         catch(IOException ioe)
         {  System.out.println("Sending error: " + ioe.getMessage());
            stop();
         }
      }
   }

   public void handle(String msg)
   {  if (msg.equals(".bye"))
      {  System.out.println("Good bye. Press RETURN to exit ...");
         stop();
      }
      else
         System.out.println(msg);
   }




   private void start() throws IOException
   {  console   = new DataInputStream(System.in);
      streamOut = new DataOutputStream(socket.getOutputStream());
      if (thread == null)
      {  client = new ChatClientThread();
         client.NewChatClientThread(this, socket);
         thread = new Thread(this);
         thread.start();
      }
   }

   public void stop()
   {  if (thread != null)
      {  thread.stop();
         thread = null;
      }
      try
      {  if (console   != null)  console.close();
         if (streamOut != null)  streamOut.close();
         if (socket    != null)  socket.close();
      }
      catch(IOException ioe)
      {  System.out.println("Error closing ..."); }
      client.close();
      client.stop();
   }


}